{% extends 'base.html' %}
{% load dict_extras %}
{% block content %}
<h1 class="h4 mb-3">运行日志{% if scene %} - {{ scene.name }}{% endif %}</h1>

<!-- 单封测试运行 -->
<div class="card mb-4">
  <div class="card-header">单封测试运行</div>
  <div class="card-body">
    <form class="row g-2 align-items-end" method="post" action="/runs/single" enctype="multipart/form-data">
      {% csrf_token %}
      <div class="col-md-4">
        <label class="form-label">邮箱</label>
        <select class="form-select" name="mailbox_id" required>
          <option value="">选择邮箱</option>
          {% for m in mailboxes %}
          <option value="{{ m.id }}">{{ m.name }} ({{ m.username }})</option>
          {% endfor %}
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">场景</label>
        <select class="form-select" name="scene_id" required>
          <option value="">选择场景</option>
          {% for s in scenes %}
          <option value="{{ s.id }}">{{ s.name }}{% if s.ai_provider %} · {{ s.ai_provider.name }}{% endif %}</option>
          {% endfor %}
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">上传 .eml（可选）</label>
        <input class="form-control" type="file" name="email_file" accept=".eml" />
      </div>
      <div class="col-md-2">
        <button type="submit" class="btn btn-primary w-100">运行</button>
      </div>
      <div class="col-12 text-muted small">说明：如选择 .eml 文件，将直接解析并处理该邮件；否则从所选邮箱取最新一封。若主题无委托单号（WT14位），将直接保存运行记录，reason=“主题无委托单号”。</div>
    </form>
    {% if single_ok == '1' %}
      <div class="alert alert-success mt-3 mb-0">{{ single_msg }}</div>
    {% elif single_ok == '0' %}
      <div class="alert alert-danger mt-3 mb-0">{{ single_msg }}</div>
    {% endif %}
  </div>
</div>

<!-- 保留原有内容 -->
<div class="card mb-4">
  <div class="card-body">
    <form class="row g-2" method="get" action="/debug/trigger-merge/">
      <div class="col-md-3">
        <label class="form-label">场景名称</label>
        <input name="scene" class="form-control" placeholder="订舱确认 或 到港通知" required>
      </div>
      <div class="col-md-2">
        <label class="form-label">PO</label>
        <input name="po_no" class="form-control" placeholder="PO123">
      </div>
      <div class="col-md-2">
        <label class="form-label">BL</label>
        <input name="bl_no" class="form-control" placeholder="BL123">
      </div>
      <div class="col-md-2">
        <label class="form-label">Booking</label>
        <input name="booking_no" class="form-control" placeholder="BK123">
      </div>
      <div class="col-md-2">
        <label class="form-label">箱号</label>
        <input name="container_no" class="form-control" placeholder="CNU1234567">
      </div>
      <div class="col-md-1 d-flex align-items-end">
        <button class="btn btn-outline-secondary w-100" type="submit">触发</button>
      </div>
      <div class="col-12 text-muted small">提示：也可直接 GET 调用此接口，例如 /debug/trigger-merge/?scene=订舱确认&po_no=PO-DEBUG-002&bl_no=BL</div>
      <div class="col-12 text-muted small">可选：vessel、voyage、pol、pod、etd、eta、ata 也可作为参数传入</div>
    </form>
  </div>
</div>

{% if merge_result %}
<div class="card mb-4">
  <div class="card-header">合并结果</div>
  <div class="card-body"><pre>{{ merge_result|safe }}</pre></div>
</div>
{% endif %}

<div class="card mb-4">
  <div class="card-header">最近运行（20条）</div>
  <div class="table-responsive">
    <table class="table table-sm mb-0">
      <thead>
        <tr>
          <th>ID</th><th>Scene</th><th>Status</th><th>Started</th><th>Finished</th><th>Reasoning</th><th>Error</th>
        </tr>
      </thead>
      <tbody>
        {% for r in recent_runs %}
        <tr>
          <td>{{ r.id }}</td>
          <td>{{ r.scene.name }}</td>
          <td>{{ r.status }}</td>
          <td>{{ r.started_at|date:'Y-m-d H:i:s' }}</td>
          <td>{{ r.finished_at|date:'Y-m-d H:i:s' }}</td>
          <td class="text-nowrap">
            {% if r.reasoning %}
              <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#reasoningModal" data-reasoning="{{ r.reasoning|escape }}">查看</button>
            {% else %}
              <span class="text-muted">-</span>
            {% endif %}
          </td>
          <td class="text-danger small">{{ r.error|default:'-' }}</td>
        </tr>
        {% empty %}
        <tr><td colspan="6" class="text-muted">暂无记录</td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>

<!-- 数据浏览器：查看/查询 + 分页 所有数据表 -->
<div class="card">
  <div class="card-header d-flex align-items-center justify-content-between">
    <div>数据浏览器（只读）</div>
    <form class="row g-2 align-items-center" method="get" action="/runs/">
      <div class="col-auto">
        <label class="form-label mb-0 me-2">数据表</label>
        <select class="form-select" name="browse_model" onchange="this.form.submit()">
          {% for m in browse_models %}
          <option value="{{ m }}" {% if m == browse_model_key %}selected{% endif %}>{{ m }}</option>
          {% endfor %}
        </select>
      </div>
      <div class="col-auto">
        <label class="form-label mb-0 me-2">关键词</label>
        <input type="text" class="form-control" name="q" value="{{ browse_q }}" placeholder="支持字符字段模糊匹配，数字匹配ID">
      </div>
      <div class="col-auto">
        <label class="form-label mb-0 me-2">每页</label>
        <input type="number" class="form-control" style="width: 100px;" name="page_size" value="{{ browse_page_size }}" min="1" max="100">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-primary">查询</button>
      </div>
    </form>
  </div>
  <div class="table-responsive">
    <table class="table table-sm mb-0">
      <thead>
        <tr>
          {% for col in browse_columns %}
          <th>{{ col }}</th>
          {% endfor %}
        </tr>
      </thead>
      <tbody>
        {% for row in browse_records %}
        <tr>
          {% for col in browse_columns %}
          <td style="white-space: pre-wrap; word-break: break-word;">{{ row|get_item:col }}</td>
          {% endfor %}
        </tr>
        {% empty %}
        <tr><td colspan="99" class="text-muted">暂无数据</td></tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  <div class="card-body py-2">
    <nav>
      <ul class="pagination pagination-sm mb-0">
        <li class="page-item {% if not browse_page_obj.has_previous %}disabled{% endif %}">
          {% if browse_page_obj.has_previous %}
            <a class="page-link" href="?browse_model={{ browse_model_key }}&q={{ browse_q }}&page_size={{ browse_page_size }}&page={{ browse_page_obj.previous_page_number }}">上一页</a>
          {% else %}
            <a class="page-link" href="#" tabindex="-1" aria-disabled="true">上一页</a>
          {% endif %}
        </li>
        <li class="page-item disabled"><span class="page-link">第 {{ browse_page_obj.number }} / {{ browse_page_obj.paginator.num_pages }} 页，共 {{ browse_page_obj.paginator.count }} 条</span></li>
        <!-- 下一页 -->
        <li class="page-item {% if not browse_page_obj.has_next %}disabled{% endif %}">
          {% if browse_page_obj.has_next %}
            <a class="page-link" href="?browse_model={{ browse_model_key }}&q={{ browse_q }}&page_size={{ browse_page_size }}&page={{ browse_page_obj.next_page_number }}">下一页</a>
          {% else %}
            <a class="page-link" href="#" tabindex="-1" aria-disabled="true">下一页</a>
          {% endif %}
        </li>
      </ul>
    </nav>
  </div>
</div>

<!-- Reasoning Modal -->
<div class="modal fade" id="reasoningModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">思考过程 Reasoning</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
      </div>
      <div class="modal-body">
        <pre class="mb-0" id="reasoningModalBody" style="white-space: pre-wrap; word-break: break-word;"></pre>
      </div>
    </div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    var modalEl = document.getElementById('reasoningModal');
    if (!modalEl) return;
    modalEl.addEventListener('show.bs.modal', function (event) {
      var button = event.relatedTarget;
      var content = button ? button.getAttribute('data-reasoning') : '';
      var bodyEl = document.getElementById('reasoningModalBody');
      if (bodyEl) bodyEl.textContent = content || '';
    });
  });
</script>
{% endblock %}